﻿using EI;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace LtMesWeb
{
    internal class Program
    {
        static int i_count = 0;
        static void Main(string[] args)
        {
           



            /*
             方式二：HTTP通信（控制台作为服务端）
            ‌1）效率‌：基于文本协议（如JSON），序列化开销较大，延迟通常在毫秒级            
            2）‌稳定性‌：依赖网络状态，需处理重试机制（如Polly库），但HTTP协议本身具备错误码规范
            3）并发能力‌：原生支持高并发，可通过ASP.NET Core的Kestrel服务器优化（如调整线程池）
            4）资源开销‌：需维护HTTP连接池，内存占用较高，且存在SSL/TLS加密成本
            5）‌场景‌：跨网络或需跨语言交互的场景（如RESTful API）
             */

            //方式二：创建监听器
            var listener = new HttpListener();
            listener.Prefixes.Add("http://localhost:8080/");
            listener.Start();
            Console.WriteLine("Listening on http://localhost:8080/");

            while (true)
            {
                // 等待请求
                var context = listener.GetContext();
                ThreadPool.QueueUserWorkItem(_ => ProcessRequest(context));
            }

            

        }



        /// <summary>
        /// 方式2：
        /// </summary>
        /// <param name="context"></param>
        static void ProcessRequest(HttpListenerContext context)
        {
            i_count++;
            Console.WriteLine("method==========================i["+ i_count.ToString() + "]");

            HttpListenerRequest request = context.Request;
            var response = context.Response;

            EI.EIInfo outBlock = new EIInfo();

         



            try
            {
                // 从请求中读取输入参数（假设是POST请求， body中有参数）
                
                if (request.HttpMethod == "POST")
                {
                    Console.WriteLine("[POST]");

                    

                    string service = request.Headers["X-service"];
                    string userid = request.Headers["X-userid"];
                    string username = request.Headers["X-username"];
                    string fore_ip = request.Headers["X-fore_ip"];

                    string authorization = request.Headers["Authorization"];

                    // 遍历所有请求头
                    //foreach (string headerName in request.Headers.AllKeys)
                    //{
                    //    string headerValue = request.Headers[headerName];
                    //    Console.WriteLine($"{headerName}: {headerValue}");
                    //}

                    Console.WriteLine("-----------------------------------------------------");

                    string str_json = null;
                    using (var reader = new System.IO.StreamReader(request.InputStream, request.ContentEncoding))
                    {
                        str_json = reader.ReadToEnd();
                    }

                    Console.WriteLine("str_json:\n" + str_json);

                    Console.WriteLine("-----------------------------------------------------");

                    DataSet dt = JsonConvert.DeserializeObject<DataSet>(str_json);

                    EI.EIInfo inBlock = new EI.EIInfo();
                    inBlock.Tables.RemoveAt(0);
                    for (int i=0;i< dt.Tables.Count;i++)
                    {
                        inBlock.Tables.Add(dt.Tables[i].Copy());
                    }

                    inBlock.sys_info.company_code = "LT";
                    inBlock.sys_info.company_name = "LT";

                    inBlock.sys_info.userid = userid;
                    inBlock.sys_info.username = username;
                    inBlock.sys_info.fore_ip = fore_ip;


                    outBlock = EI.EITuxedo.CallService(service, inBlock);

                    //分页；

                    //错误判断；返回【flag,mes】；
                    outBlock.Tables.Add("SYS");
                    outBlock.Tables["SYS"].Columns.Add("FLAG");
                    outBlock.Tables["SYS"].Columns.Add("MSG");
                    outBlock.Tables["SYS"].Rows.Add(outBlock.sys_info.flag, outBlock.sys_info.msg);

                   
                    
                    



                }
                else if (request.HttpMethod == "GET")
                {
                    // 获取查询字符串参数[字符不应该超过2000个，否则建议头参数；]
                    NameValueCollection queryString = request.QueryString;

                    //获取特定参数值 string name = queryParams["name"] ?? "未知";
                    string str_sql = queryString["str_sql"]??"null";
                    // 或者遍历所有参数
                    //foreach (string key in queryString.AllKeys)
                    //{
                    //    string value = queryString[key];
                    //    Console.WriteLine($"GET参数: {key} = {value}");
                    //}
                    outBlock = EF.Utility.ExecQuery(str_sql);
                }
                  


       

                



                // 调用Legacy DLL的静态方法
                

                string result = JsonConvert.SerializeObject(outBlock);
                // 返回结果
                byte[] buffer = Encoding.UTF8.GetBytes(result);
                response.ContentLength64 = buffer.Length;
                response.OutputStream.Write(buffer, 0, buffer.Length);
            }
            catch (Exception ex)
            {
                // 返回错误
                byte[] buffer = Encoding.UTF8.GetBytes($"Error: {ex.Message}");
                response.ContentLength64 = buffer.Length;
                response.OutputStream.Write(buffer, 0, buffer.Length);
            }
            finally
            {
                response.OutputStream.Close();
            }
        }


        /*方式一：进程参数传递（Console.WriteLine + Process类）
        ‌效率‌：通过标准输入/输出流传输，存在进程启动开销，适合低频批量数据
        1)稳定性‌：进程崩溃会导致通信中断，需监控子进程状态           
        2)‌并发能力‌：每次调用需启动新进程，并发性能差，资源竞争风险高            
        ‌3)资源开销‌：频繁进程创建/销毁消耗CPU，且传输大数据时内存压力显著            
        4)场景‌：简单脚本调用或遗留系统集成，不推荐高性能场景

        通过args接受参数，把返回结果写入Console中，调用者通过process.StandardOutput.ReadToEndAsync();从Console读取结果；
        单独测试亦可：D:\1_dev\龙腾\龙腾WebApi\LTWebApi\LtMesWeb\bin\Debug>LtMesWeb.exe "select count(*) from tmm0001"

         static void Main(string[] args)
        {
        Console.WriteLine("begin==========================");


        if (args.Length > 0  && args.Length <2 )
        {
            // 直接调用 .NET 3.5 DLL 中的静态方法
            EI.EIInfo outBlock = EF.Utility.ExecQuery(args[0]);
            string json = JsonConvert.SerializeObject(outBlock);
            Console.WriteLine(json);


        }
        if (args.Length>= 2)
        {


            EI.EIInfo inBlock = new EI.EIInfo();

            inBlock.sys_info.company_code = "LT";
            inBlock.Tables[0].Rows.Add();
            EI.EIInfo outBlock = EI.EITuxedo.CallService("qmcc201_inq", inBlock);
            string json = JsonConvert.SerializeObject(outBlock);
            Console.WriteLine(json);

        }
        }
         */


        /* 方式三：管道通讯方式，【效率高，不时候大文件，小于<1ms】
         * 
          class Program
    {
        static void Main()
        {
            while (true)
            {
                using (var server = new NamedPipeServerStream("LegacyStaticMethods"))
                {
                    Console.WriteLine("等待 ASP.NET Core 连接...");
                    server.WaitForConnection();
                    Console.WriteLine("已连接");
                    
                    // 处理请求
                    ProcessClientRequest(server);
                }
            }
        }
        
        static void ProcessClientRequest(NamedPipeServerStream server)
        {
            var reader = new StreamReader(server);
            var writer = new StreamWriter(server);
            
            try
            {
                while (server.IsConnected)
                {
                    var request = reader.ReadLine();
                    if (string.IsNullOrEmpty(request)) continue;
                    
                    Console.WriteLine($"收到请求: {request}");
                    var response = ExecuteStaticMethod(request);
                    
                    writer.WriteLine(response);
                    writer.Flush();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"错误: {ex.Message}");
            }
        }
        
        static string ExecuteStaticMethod(string request)
        {
            try
            {
                var parts = request.Split('|');
                var methodName = parts[0];
                
                switch (methodName)
                {
                    case "Method1":
                        var input = parts[1];
                        return Legacy35Namespace.StaticClass.StaticMethod1(input);
                        
                    case "Method2":
                        var a = int.Parse(parts[1]);
                        var b = int.Parse(parts[2]);
                        return Legacy35Namespace.StaticClass.StaticMethod2(a, b).ToString();
                        
                    default:
                        return $"ERROR: Unknown method {methodName}";
                }
            }
            catch (Exception ex)
            {
                return $"ERROR: {ex.Message}";
            }
        }
    }
         
         */


    }
}
